package cn.jg.framework.common.bean;

import com.github.pagehelper.Page;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author fanfever
 * @date 2017/4/1
 */

@FunctionalInterface
public interface Converter<S, T> {

	/**
	 * convert dto
	 *
	 * @param s source bean
	 * @return target bean
	 */
	T convert(final S s);

	/**
	 * convert dto list
	 *
	 * @param input source bean list
	 * @return target bean list
	 */
	default List<T> convertToList(final List<S> input) {
		if (input instanceof Page) {
			Page<T> page = new Page<>();
			if (!CollectionUtils.isEmpty(input)) {
				page.addAll(input.stream().map(this::convert).collect(toList()));
			}
			page.setTotal(((Page) input).getTotal());
			page.setPageNum(((Page) input).getPageNum());
			page.setPageSize(((Page) input).getPageSize());
			return page;
		} else if (CollectionUtils.isEmpty(input)) {
			return Collections.emptyList();
		} else {
			return input.stream().map(this::convert).collect(toList());
		}


	}
}
